package com.calf.module.sms.controller;

import com.calf.cn.aspect.MethodLog;
import com.calf.cn.controller.BaseController;
import com.calf.cn.entity.DataTables;
import com.calf.cn.service.BaseManager;
import com.calf.cn.utils.DateUtil;
import com.calf.cn.utils.SearchUtil;
import com.calf.cn.utils.SmsUtilxml;
import com.calf.module.common.enumsatate.SmsEnum;
import com.calf.module.jpush.JPushUtil;
import com.calf.module.loan.entity.Customer;
import com.calf.module.message.entity.MessageConstant;
import com.calf.module.sms.entity.Sms;
import com.calf.module.sms.entity.SmsConstant;
import com.calf.module.util.Utils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/sms")
public class SmsController implements BaseController<Sms> {

	@Autowired
	private BaseManager baseManager;

	@Override
	public String home() {
		return "sms/smslist";
	}

	@Override
	public DataTables<Sms> initTable(HttpServletRequest request) {
		@SuppressWarnings("unchecked")
		Map<String, Object> parameters = SearchUtil.convertorEntitysToMap(request.getParameterMap());
		String sEcho = (String) parameters.get("sEcho");
		List<Sms> sms = baseManager.query(Sms.class, parameters);
//		sms.forEach(singleSms -> singleSms.setPushNumber(singleSms.getSmsPhones().split(",").length));
		int total = baseManager.get("Sms.queryCount", parameters);
		return new DataTables<Sms>(sEcho, sms, sms.size(), total);
	}

	@Override
	public String addAndUpdateHome(Model model, String id) {
		model.addAttribute("flag", id);
		return "sms/addsms";
	}

	@Override
	public int saveAdd(Sms entity) {
		/*
		 * String result = SmsUtil.getSms(entity.getSmsPhones(),
		 * entity.getSmsContent()); System.out.println(result); //获取操作者帐号
		 * Subject currentUser = SecurityUtils.getSubject();
		 *
		 * Sms sms = new Sms(); sms.setSmsName("测试短信");
		 * sms.setSmsCode("test-template");
		 * sms.setSmsContent(entity.getSmsContent());
		 * sms.setCreateMan(String.valueOf(currentUser.getPrincipal()));
		 * sms.setCreateTime(new Date());
		 * sms.setModifyMan(String.valueOf(currentUser.getPrincipal()));
		 * sms.setModifyTime(new Date());
		 * sms.setState(SmsConstant.state.active);
		 * sms.setSmsTemplateId(MessageConstant.generateId()); if
		 * (entity.getSendType() == 1) {
		 * sms.setSmsPhones(entity.getSmsPhones()); } else {
		 * sms.setSmsPhones(null); } return baseManager.insert(sms) ;
		 */
		return 0;
	}

	@ResponseBody
	@RequestMapping(value = "/saveAdd.htm", method = RequestMethod.POST)
	public int saveAdd(Sms entity, String flag, HttpServletRequest request) {
		String type = request.getParameter("sendType");
		// 短信推送
		if (flag.equals("0")) {
			String result = "";
			if (type.equals("1")) {
				SmsUtilxml.getSms(entity.getSmsPhones(), entity.getSmsContent());
				entity.setSmsPhones(entity.getSmsPhones());
			}
			if (type.equals("2")) {
				StringBuffer sb = new StringBuffer();
				List<Customer> customers = baseManager.query(Customer.class);
				for (Customer customer : customers) {
					sb.append(customer.getPhoneNum() + ",");
				}
				String phones = sb.substring(0, sb.length() - 1);
				SmsUtilxml.getSms(phones, entity.getSmsContent());//发送短信api
				entity.setSmsPhones(phones);
			}
			System.out.println(result);
			// 获取操作者帐号
			Subject currentUser = SecurityUtils.getSubject();

			entity.setSmsName("短信");
			entity.setSmsCode("1");
			entity.setCreateMan(String.valueOf(currentUser.getPrincipal()));
			entity.setCreateTime(DateUtil.dateFormat());
			entity.setModifyMan(String.valueOf(currentUser.getPrincipal()));
			entity.setModifyTime(DateUtil.dateFormat());
			entity.setState(SmsConstant.state.active);
			entity.setSmsTemplateId(MessageConstant.generateId());
			return baseManager.insert(entity);
		}
		// 极光推送
		else {
			String target = request.getParameter("target");
			String isTime = request.getParameter("isTime");
			String timePushTime = request.getParameter("timePushTime");
			String pushType =request.getParameter("pushType");
			String temp =  request.getParameter("productId");

			StringBuffer buffer = new StringBuffer();
			StringBuffer sb = new StringBuffer();
			String phone = "";
			String content = request.getParameter("content");
			String title = request.getParameter("title");
			String url = request.getParameter("url");
			String alias = "";

			switch (type){
				case "1":	//指定用户
					String[] phones = entity.getSmsPhones().split(",");
					for (String p : phones) {
						Customer customer = baseManager.get(Customer.class,new Object[] { p });
						if(Utils.isEmpty(customer)){
							continue;
						}
						buffer.append(customer.getCustomerId() + ",");
					}
					if (buffer.length()-1 == 0){
						throw new NullPointerException("用户都不不存在!");
					}
					alias = buffer.substring(0, buffer.length() - 1);
					break;

				case "2":	//所有用户
					List<Customer> customers = baseManager.queryAll(Customer.class, new HashMap<>());
					for (Customer customer : customers) {
						sb.append(customer.getPhoneNum() + ",");
						buffer.append(customer.getCustomerId() + ",");
					}
					alias = buffer.substring(0, buffer.length() - 1);
					phone = sb.substring(0, sb.length() - 1);
					entity.setSmsPhones(phone);
					break;

				case "3":	//IOS用户
					List<Customer> customers3 = baseManager.queryByString("Customer.queryByPhoneType", SmsEnum.PHONE_TYPE_IPHON.getState());
					for (Customer customer : customers3) {
						sb.append(customer.getPhoneNum() + ",");
						buffer.append(customer.getCustomerId() + ",");
					}
					alias = buffer.substring(0, buffer.length() - 1);
					phone = sb.substring(0, sb.length() - 1);
					entity.setSmsPhones(phone);
					break;

				case "4":	//android用户
					List<Customer> customers4 = baseManager.queryByString(
							"Customer.queryByPhoneType", SmsEnum.PHONE_TYPE_ANDROID.getState());
					for (Customer customer : customers4) {
						sb.append(customer.getPhoneNum() + ",");
						buffer.append(customer.getCustomerId() + ",");
					}
					alias = buffer.substring(0, buffer.length() - 1);
					phone = sb.substring(0, sb.length() - 1);
					entity.setSmsPhones(phone);
					break;
			}

			target = "1";//ios target为1时推送H5 target不存在推送到原生首页
			   			 //android 先判断url是否存在，url存在跳H5，url不存在判断target是否存在，target=2跳到还款页面， target为别的任意值跳原生首页

			if (StringUtils.equals(isTime,"1")){
				// 非定时推送任务 立即推送
				entity.setIsTime(1);
				entity.setTimePushTime(null);

				//推送
				JPushUtil.jSend_notification(alias, content, title, url, target);

				entity.setCreateTime(DateUtil.dateFormat());
				entity.setPushSuccessNumber(alias.split(",").length);//推送成功个数
			}else{
				entity.setIsTime(2);
				entity.setTimePushTime(timePushTime);//设置定时时间
				entity.setCreateTime(DateUtil.dateFormat());
			}

			Subject currentUser = SecurityUtils.getSubject();
			entity.setSmsName(title);
			entity.setSmsContent(content);
			entity.setSmsCode("2");
			entity.setCreateMan(String.valueOf(currentUser.getPrincipal()));
			entity.setCreateTime(DateUtil.dateFormat());
			entity.setModifyMan(String.valueOf(currentUser.getPrincipal()));
			entity.setModifyTime(DateUtil.dateFormat());
			entity.setState(SmsConstant.state.active);
			entity.setSmsTemplateId(MessageConstant.generateId());

			if (StringUtils.isEmpty(url)) entity.setUrl(url);

			entity.setAlias(alias);
			entity.setTarget(Integer.parseInt(target));

			int num = baseManager.insert(entity);
			return num;
		}
	}

	@Override
	public int delete(Long id) {
		return 0;
	}

	@Override
	public int saveUpdate(Sms entity) {
		return 0;
	}

	@Override
	@MethodLog(operType = "删除")
	public int delete(String id) {
		return baseManager.delete(Sms.class, new Object[] { id });
	}

	public static void main(String[] args) {
		Customer customers = new Customer();
		System.out.println(customers);
		if(!Utils.isEmpty(customers)){
			System.out.println("为空");
		}else{
			System.out.println("不为空");
		}
	}

}
